<?php
namespace Home\Controller;
use Think\Controller;
class JieController extends CommonController {

	public function index()
	{

        // $obj =M('question');

        // //  在User模型中启动事务
        // $obj ->startTrans();

        // M("cate")->add(['cname'=>'学并思1']);

        // M("cate")->add(['cname'=>'学并思2']);


        // M("cate")->add(['cname'=>'学并思3']);


        // if (1==1){
        //     // 提交事务
        //      $obj->commit(); 
        // }else{
        //    // 事务回滚
        //      $obj ->rollback(); 
        // }

        // $qid = $_GET['qid'];

        // $qid = I('get.qid');

        // var_dump($qid);

        // $qid = addslashes($qid);


        // var_dump($qid);

        // $sql="select * from question where qid=':s'";

        // var_dump($sql);


        // M('collect')->where(['qid'=>$qid,'uid'=>$uid])->find();

        // // $res = M()->query($sql);


        // var_dump($res);






        // exit;
		$qid = I('get.qid');

		$uid = $_SESSION['uid'];

		$is_collect = M('collect')->where(['qid'=>$qid,'uid'=>$uid])->find();

		$question = M('question t1')->field("t1.*,t2.nickname,t2.face,t3.cname")->join("user t2 on t1.uid=t2.uid")->join("cate t3 on t1.cid=t3.cid")->where(['t1.qid'=>$qid])->find();

		// var_dump($question);


		// $sql = "select * from question t1 inner join user t2 on t1.uid = t2.uid inner join cate t3 on t1.cid = t3.cid where qid={$qid}";
		// 
		$answer = M('answer t1')->field("t1.*,t2.nickname,t2.face")->join("user t2 on t1.uid=t2.uid")->where(['t1.qid'=>$qid])->select();


		foreach ($answer as $k => $row) {

			$answer[$k]['is_zan'] = M('zan')->where(['aid'=>$row['aid'],'uid'=>$uid])->find();
		}


        $appId= 'wxbac82045a637c02e';
        // 必填，公众号的唯一标识
        $timestamp=time();
         // 必填，生成签名的时间戳
        $nonceStr=$this->nonceStr(); // 必填，生成签名的随机串

        $url = "http://1o533n8683.imwork.net".U('home/jie/index',array('qid'=>$qid));

        $at = $this->getAt();

        $jsapi_ticket = $this->jsapi_ticket($at);


        $str = "jsapi_ticket=".$jsapi_ticket."&noncestr=".$nonceStr."&timestamp=".$timestamp."&url=".$url;

        $signature = sha1($str);

        $this->assign('signature',$signature);
        $this->assign('nonceStr',$nonceStr);
        $this->assign('appId',$appId);
        $this->assign('timestamp',$timestamp);
        $this->assign('url',$url);
        // $signature: '',// 必填，签名，见附录1

		$hotques = D('question')->getHotTen();

		$this->assign('hotques',$hotques);
		$this->assign('ques',$question);
		$this->assign('is_collect',$is_collect);
		$this->assign('answer',$answer);
        $this->assign('title',$question['title']);
		$this->display();
	}

    public function nonceStr($num=16)
    {
        $str = '';

        $abc = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";

        for ($i=0; $i <16 ; $i++) { 
            $str .= $abc[mt_rand(0,strlen($abc))];
        }
        return $str;
    }

    public function jsapi_ticket($at)
    {
       if(S('jsapi_ticket')){

            return S('jsapi_ticket');

        }else{

            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$at."&type=jsapi";

            $data = file_get_contents($url);

            var_dump($data);

            $data = json_decode($data,true);

            if(isset($data['ticket'])){

                S('jsapi_ticket',$data['ticket'],7200);

                return $data['ticket'];
            }

        }
    }
    public function getAt()
    {

        if(S('access_token')){

            return S('access_token');

        }else{

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbac82045a637c02e&secret=7c320fea54e77a01fcc59ff7060b04e2";

            $data = file_get_contents($url);

            $data = json_decode($data,true);

            if(isset($data['access_token'])){

                S('access_token',$data['access_token'],7200);

                return $data['access_token'];
            }

        }
        
    }
    public function add(){

    	$cate = M('cate')->select();
    	$question = D('Verify')->getRandOne();
    	$this->assign('question',$question);
    	$this->assign('cate',$cate);
    	$this->display();
    }

    public function upload()
    {
    	$upload = new \Think\Upload();
    	// 实例化上传类
	    $upload->maxSize   =     3145728 ;// 设置附件上传大小
	    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
	    $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
	    $upload->savePath  =     ''; // 设置附件上传（子）目录
	    // 上传文件 
	    $info   =   $upload->upload();

	    if(!$info) {// 上传错误提示错误信息
	        $this->error($upload->getError());
	        echo "error";
	    }else{// 上传成功

	    	$info = current($info);

	    	$path = __ROOT__."/Uploads/".$info['savepath'].$info['savename'];

	    	$data = array(
	    		'code'=>0,
	    		'msg'=>'图片',
	    		'data'=>array(
	    			'src'=>$path,
	    			'title'=>''
	    			)
	    	);

	    	echo json_encode($data);

	    	
	    }
 
    }

    public function addjie()
    {
    	$data = I('post.');

        // $data = $_POST;

    	$uid = $_SESSION['uid'];

    	$vercode = I('post.vercode');

    	if($vercode!=$_SESSION['answer']){

      		$this->ajaxReturn(['error'=>1,'info'=>'人类验证不通过']);
      	}

      	$user = M('user')->find($uid);

      	if($user['kiss']<$data['kiss']){
      		$this->ajaxReturn(['error'=>1,'info'=>'飞吻不够']);
      	}

    	$data['uid'] =$uid;

    	$data['ctime'] = time();

    	$qid = M('question')->add($data);

    	// $sql ="update user set kiss=kiss-20 where uid=13";

    	M('user')->where(['uid'=>$uid])->setDec('kiss',$data['kiss']); // 用户的积分减1

    	$this->ajaxReturn(['error'=>0,'info'=>'发布成功','url'=>U('home/jie/index',array('qid'=>$qid))]);
    }

    public function addanser()
    {
    	$data = I('post.');

    	$uid = $_SESSION['uid'];

    	$data['uid'] = $uid;

    	$data['ctime'] = time();

    	$qid = M('answer')->add($data);

    	M('question')->where(['qid'=>$data['qid']])->setInc('answer_num'); // 用户的积分减1

    	$this->ajaxReturn(['error'=>0,'info'=>'回复成功']);

    }

    public function collect()
    {
    	$data = I('post.');

    	$data['uid'] = $_SESSION['uid'];

    	$res = M('collect')->where($data)->find();

    	if($res){

    		M('collect')->where($data)->delete();

    		$this->ajaxReturn(['error'=>0,'info'=>'取消收藏']);

    	}else{

    		$data['ctime'] = time();

    		M('collect')->add($data);

    		$this->ajaxReturn(['error'=>1,'info'=>'收藏']);

    	}
    }

    public function zan()
    {
    	$data = I('post.');

    	$data['uid'] = $_SESSION['uid'];

    	$res = M('zan')->where($data)->find();

    	if($res){

    		M('zan')->where($data)->delete();

    		M('answer')->where(['aid'=>$data['aid']])->setDec('zan_num'); // 用户的积分减1

    		$this->ajaxReturn(['error'=>0,'info'=>'取消']);

    	}else{

    		$data['ctime'] = time();

    		M('zan')->add($data);

    		M('answer')->where(['aid'=>$data['aid']])->setInc('zan_num'); 

    		$this->ajaxReturn(['error'=>1,'info'=>"点赞"]);

    	}
    }
}